-- ============================================
-- ROCKET CASINO - MACHINE A SOUS (ecran unique)
-- Base : ton fichier slot_machine.lua (rouleaux 3x3, ligne de paiement,
--        pluie de dollars) + reglage de mise et bouton QUITTER.
-- Necessite : Advanced Computer + Advanced Monitor (couleur)
-- Fichiers requis dans le meme dossier : login.lua, client_solde.lua
-- Le monitor est directement la machine a sous : pas de banniere a part,
-- pas de popup. Connexion -> jeu -> QUITTER -> connexion du joueur suivant.
-- ============================================

-- === CONFIGURATION ===
local SYMBOLS = {
    { symbol = "\3",  color = colors.red,       value = 2,  name = "Coeur" },
    { symbol = "\4",  color = colors.yellow,    value = 3,  name = "Carreau" },
    { symbol = "\5",  color = colors.orange,    value = 5,  name = "Trefle" },
    { symbol = "\6",  color = colors.green,     value = 8,  name = "Pique" },
    { symbol = "\15", color = colors.lightBlue, value = 15, name = "Soleil" },
    { symbol = "7",   color = colors.magenta,   value = 50, name = "Sept" },
    { symbol = "R",   color = colors.red,       value = 75, name = "Team Rocket" },
}

local MISE_MIN, MISE_MAX, MISE_STEP, MISE_DEFAULT = 1, 20, 1, 1
local bet = MISE_DEFAULT

local bank = dofile("client_solde.lua")

-- === PERIPHERIQUES ===
local mon = peripheral.find("monitor")
if not mon then
    error("Aucun monitor trouve ! Colle un Advanced Monitor a cote du computer.")
end

mon.setTextScale(0.5)
term.redirect(mon)
local w, h = term.getSize()

local login = dofile("login.lua")

local function centerText(y, text, textColor, bgColor)
    term.setBackgroundColor(bgColor or colors.black)
    term.setTextColor(textColor or colors.white)
    local x = math.floor((w - #text) / 2) + 1
    term.setCursorPos(x, y)
    term.write(text)
end

local function fillArea(x1, y1, x2, y2, bg)
    term.setBackgroundColor(bg)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", x2 - x1 + 1))
    end
end

-- === BOUTONS TACTILES (meme principe que login.lua) ===
local function drawButton(buttons, id, x, y, label, bg, fg)
    local text = " " .. label .. " "
    term.setBackgroundColor(bg)
    term.setTextColor(fg or colors.white)
    term.setCursorPos(x, y)
    term.write(text)
    table.insert(buttons, { id = id, x1 = x, x2 = x + #text - 1, y = y })
    return x + #text
end

local function hitButton(buttons, x, y)
    for _, btn in ipairs(buttons) do
        if x >= btn.x1 and x <= btn.x2 and y == btn.y then
            return btn.id
        end
    end
    return nil
end

-- === GEOMETRIE DES ROULEAUX ===
local REEL_COUNT = 3
local SYM_W, SYM_H = 7, 3
local SEP_H = 1
local REEL_GAP = 2

local totalReelWidth = REEL_COUNT * SYM_W + (REEL_COUNT - 1) * REEL_GAP
local reelsLeft = math.max(1, math.floor((w - totalReelWidth) / 2) + 1)
local reelsTop = 8   -- laisse la place au titre + infos + boutons

local function reelX(i)
    return reelsLeft + (i - 1) * (SYM_W + REEL_GAP)
end

local rowTopY = reelsTop
local sep1Y = rowTopY + SYM_H
local rowMidY = sep1Y + SEP_H
local sep2Y = rowMidY + SYM_H
local rowBotY = sep2Y + SEP_H
local reelBottom = rowBotY + SYM_H - 1

local function randomSymbol()
    return math.random(1, #SYMBOLS)
end

-- === DESSIN D'UN ROULEAU ===
local function drawSymbolBox(x1, y1, idx, isPayline)
    local sym = SYMBOLS[idx]
    local x2 = x1 + SYM_W - 1
    local y2 = y1 + SYM_H - 1
    term.setBackgroundColor(colors.black)
    for y = y1, y2 do
        term.setCursorPos(x1, y)
        term.write(string.rep(" ", SYM_W))
    end
    term.setTextColor(sym.color)
    local midY = y1 + math.floor(SYM_H / 2)
    local midX = x1 + math.floor((SYM_W - 1) / 2)
    term.setCursorPos(midX, midY)
    term.write(sym.symbol)

    if isPayline then
        term.setTextColor(colors.yellow)
        term.setCursorPos(x1, midY)
        term.write(">")
        term.setCursorPos(x2, midY)
        term.write("<")
    end
end

local function drawSeparator(x1, y, isPayline)
    term.setBackgroundColor(colors.black)
    term.setTextColor(isPayline and colors.yellow or colors.gray)
    term.setCursorPos(x1, y)
    term.write(string.rep("-", SYM_W))
end

local function drawReel(i, reel)
    local x = reelX(i)
    drawSymbolBox(x, rowTopY, reel.top, false)
    drawSeparator(x, sep1Y, true)
    drawSymbolBox(x, rowMidY, reel.mid, true)
    drawSeparator(x, sep2Y, true)
    drawSymbolBox(x, rowBotY, reel.bot, false)
end

local function drawAllReels(reels)
    for i, reel in ipairs(reels) do
        drawReel(i, reel)
    end
end

-- === HEADER / BOUTONS / MESSAGES / FOOTER ===
local function drawHeader(player, points)
    fillArea(1, 1, w, 3, colors.black)
    centerText(1, "=== ROCKET CASINO ===", colors.red)
    centerText(2, "MACHINE A SOUS - " .. player, colors.yellow)
    centerText(3, "Points : " .. points .. "   Mise : " .. bet, colors.lime)
end

local function drawButtonsRow()
    fillArea(1, 5, w, 5, colors.black)
    local labels = { { "BET_DOWN", "-MISE", colors.red }, { "BET_UP", "+MISE", colors.green },
                      { "SPIN", "TOURNER", colors.orange }, { "QUIT", "QUITTER", colors.gray } }

    local totalW = 0
    for _, l in ipairs(labels) do totalW = totalW + (#l[2] + 2) end
    totalW = totalW + (#labels - 1)

    local buttons = {}
    local cursor = math.max(1, math.floor((w - totalW) / 2) + 1)
    for _, l in ipairs(labels) do
        local fg = (l[3] == colors.orange) and colors.black or colors.white
        cursor = drawButton(buttons, l[1], cursor, 5, l[2], l[3], fg) + 1
    end
    return buttons
end

local function drawMessage(text, textColor)
    fillArea(1, 6, w, 6, colors.black)
    if text then
        centerText(6, text, textColor or colors.lightGray)
    end
end

local function drawFooter(text, textColor)
    fillArea(1, reelBottom + 1, w, h, colors.black)
    if text then
        centerText(reelBottom + 2, text, textColor or colors.lightGray)
    end
end

-- === ANIMATION DE PLUIE DE DOLLARS (sur gain) ===
local function dollarRain(ticks)
    local drops = {}
    for i = 1, 12 do
        drops[i] = { x = math.random(1, w), y = math.random(-10, 0) }
    end

    for t = 1, ticks do
        for _, d in ipairs(drops) do
            term.setBackgroundColor(colors.black)
            term.setCursorPos(d.x, d.y)
            term.write(" ")
            d.y = d.y + 1
            if d.y > h then
                d.x = math.random(1, w)
                d.y = math.random(-6, 0)
            elseif d.y >= 1 then
                term.setTextColor(colors.lime)
                term.setCursorPos(d.x, d.y)
                term.write("$")
            end
        end
        sleep(0.06)
    end

    for _, d in ipairs(drops) do
        term.setBackgroundColor(colors.black)
        term.setCursorPos(d.x, math.min(d.y, h))
        term.write(" ")
    end
end

-- === LOGIQUE DE GAIN ===
local function evaluateWin(i1, i2, i3, currentBet)
    if i1 == i2 and i2 == i3 then
        return SYMBOLS[i1].value * currentBet, "JACKPOT ! 3x " .. SYMBOLS[i1].name
    elseif i1 == i2 or i2 == i3 or i1 == i3 then
        local matchIdx = (i1 == i2) and i1 or ((i2 == i3) and i2 or i1)
        return math.floor(SYMBOLS[matchIdx].value / 2) * currentBet, "Petit gain ! 2x " .. SYMBOLS[matchIdx].name
    else
        return 0, nil
    end
end

-- === UNE MANCHE ===
local function playRound(player, points)
    if points < bet then
        drawMessage("PLUS ASSEZ DE POINTS !", colors.red)
        sleep(2)
        return points
    end

    local newBal1, err1 = bank.addBalance(player, -bet)
    if not newBal1 then
        drawMessage(err1 or "Erreur banque, reessaie.", colors.red)
        sleep(2)
        return points
    end
    points = newBal1

    local reels = {}
    for i = 1, REEL_COUNT do
        reels[i] = { top = randomSymbol(), mid = randomSymbol(), bot = randomSymbol() }
    end

    local stopTicks = { 14, 20, 26 }
    local maxTick = stopTicks[REEL_COUNT]

    drawHeader(player, points)
    drawFooter("Les rouleaux tournent...", colors.white)

    for tick = 1, maxTick do
        for i, reel in ipairs(reels) do
            if tick <= stopTicks[i] then
                reel.top = reel.mid
                reel.mid = reel.bot
                reel.bot = randomSymbol()
            end
        end
        drawAllReels(reels)
        sleep(0.04 + tick * 0.004)
    end

    local i1, i2, i3 = reels[1].mid, reels[2].mid, reels[3].mid
    local gain, message = evaluateWin(i1, i2, i3, bet)

    if gain > 0 then
        local newBal2 = bank.addBalance(player, gain)
        points = newBal2 or points
    end

    drawHeader(player, points)

    if gain > 0 then
        drawFooter(message .. " (+" .. gain .. ")", colors.lime)
        dollarRain(20)
        drawAllReels(reels)
        drawHeader(player, points)
        drawFooter(message .. " (+" .. gain .. ")", colors.lime)
    else
        drawFooter("Perdu... reessaie !", colors.red)
    end

    sleep(1.5)
    return points
end

-- === SESSION DE JEU (un joueur, jusqu'a QUITTER) ===
local function runSession()
    local player = login.authenticate("Qui joue au Rocket Casino ?")
    local points = bank.getBalance(player)
    bet = MISE_DEFAULT

    local idleReels = {
        { top = 1, mid = 1, bot = 1 },
        { top = 2, mid = 2, bot = 2 },
        { top = 3, mid = 3, bot = 3 },
    }

    local playing = true
    while playing do
        drawHeader(player, points)
        local buttons = drawButtonsRow()
        drawMessage(nil)
        drawAllReels(idleReels)
        drawFooter("Mise min " .. MISE_MIN .. " - max " .. MISE_MAX, colors.gray)

        local _, _, x, y = os.pullEvent("monitor_touch")
        local pressed = hitButton(buttons, x, y)

        if pressed == "BET_DOWN" then
            bet = math.max(MISE_MIN, bet - MISE_STEP)
        elseif pressed == "BET_UP" then
            bet = math.min(MISE_MAX, bet + MISE_STEP)
        elseif pressed == "SPIN" then
            points = playRound(player, points)
        elseif pressed == "QUIT" then
            playing = false
        end
    end
end

-- === PROGRAMME PRINCIPAL ===
while true do
    runSession()
end